/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.meta.service.setting.impl;

import cn.hutool.core.io.FileUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.google.common.base.Strings;
import com.je.common.base.DynaBean;
import com.je.common.base.service.CommonService;
import com.je.common.base.service.MetaService;
import com.je.common.base.service.rpc.DocumentInternalRpcService;
import com.je.common.base.util.StringUtil;
import com.je.ibatis.extension.conditions.ConditionsWrapper;
import com.je.meta.service.setting.SytemSettingPlanService;
import com.je.meta.setting.PlatformSystemConfig;
import com.je.meta.setting.SettingException;
import com.je.meta.setting.SystemSetting;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;

/**
 * 系统设置方案实现
 */
@Service
public class SytemSettingPlanServiceImpl implements SytemSettingPlanService {

    @Autowired
    private DocumentInternalRpcService documentInternalRpcService;

    @Autowired
    private MetaService metaService;
    @Autowired
    private CommonService commonService;

    /**
     * 全局系统配置
     */
    private static final PlatformSystemConfig GLOBAL_PLATFORM_CONFIG = new PlatformSystemConfig();

    /**
     * 查看所有方案
     */
    @Override
    public List<DynaBean> loadSettingPlans() {
        List<DynaBean> sysVars = metaService.select("JE_CORE_SETPLAN", ConditionsWrapper.builder().orderByDesc("SY_CREATETIME"));
        return sysVars;
    }

    /**
     * 修改保存方案
     */
    @Override
    public void saveSettingPlan(String settingPlanCode, String setplanId, DynaBean values) throws SettingException {
        SystemSetting setting = GLOBAL_PLATFORM_CONFIG.findChildSetting(settingPlanCode, "");
        if (setting == null) {
            throw new SettingException("Can't find the system setting!");
        }
        List<String> itemKeys = setting.getItemKeys();
        HashMap<String, Object> planValues = values.getValues();
        //查找需要更新的配置
        DynaBean dynaBean = new DynaBean();
        for (String key : planValues.keySet()) {
            if (itemKeys.contains(key)) {
                dynaBean.set(key, values.get(key));
            }
        }

        dynaBean.table("JE_CORE_SETPLAN");
        dynaBean.setStr("JE_CORE_SETPLAN_ID", setplanId);
        metaService.update(dynaBean);
    }

    /**
     * 查看某个方案信息
     */
    @Override
    public SystemSetting loadSettingPlanInfo(String setplanId, String settingPlanCode) {
        DynaBean dynaBean = metaService.selectOneByPk("JE_CORE_SETPLAN", setplanId);
        SystemSetting findedSetting = GLOBAL_PLATFORM_CONFIG.findChildSetting(settingPlanCode, "");
        HashMap<String, Object> values = dynaBean.getValues();
        for (String key : values.keySet()) {
            findedSetting.addItem(key, "", String.valueOf(values.get(key)), "");
        }
        return findedSetting;
    }

    /**
     * 新添方案
     */
    @Override
    public void insertSettingPlan(String settingPlanCode, DynaBean dynaBean) throws SettingException {
        SystemSetting setting = GLOBAL_PLATFORM_CONFIG.findChildSetting(settingPlanCode, "");
        if (setting == null) {
            throw new SettingException("Can't find the system setting!");
        }
        List<String> itemKeys = setting.getItemKeys();
        DynaBean insertPlan = new DynaBean("JE_CORE_SETPLAN", false);

        HashMap<String, Object> planValues = dynaBean.getValues();
        for (String key : planValues.keySet()) {
            if (itemKeys.contains(key)) {
                insertPlan.set(key, planValues.get(key));
            }
        }
        commonService.buildModelCreateInfo(insertPlan);
        metaService.insert(insertPlan);
    }

    /**
     * 删除某个方案信息
     */
    @Override
    public void deleteSettingPlan(String setplanId) {
        metaService.delete("JE_CORE_SETPLAN", ConditionsWrapper.builder().eq("JE_CORE_SETPLAN_ID", setplanId));
    }

    @Override
    public DynaBean loadPlanAndLoginConfig(String code) {
        DynaBean dynaBean = null;
        List<DynaBean> dynaBeanList = metaService.select("JE_CORE_SETPLAN", ConditionsWrapper.builder().eq("JE_SYS_PATHSCHEME", code));
        if (dynaBeanList != null && dynaBeanList.size() > 0) {
            dynaBean = dynaBeanList.get(0);
        } else {
            //取默认方案数据
            List<DynaBean> defaultList = metaService.select("JE_CORE_SETPLAN", ConditionsWrapper.builder().eq("SETPLAN_IS_DEFULT", "1"));
            dynaBean = defaultList.get(0);
        }


        //取登录设置
        List<DynaBean> list = metaService.select("JE_CORE_SETTING",
                ConditionsWrapper.builder().in("CODE", "JE_SYS_ENCRYPT", "JE_SYS_ENCRYPT_FIELD", "JE_CORE_VERIFY", "JE_CORE_PHONELOGIN", "JE_CORE_PHONEREPASSWORD", "JE_SYS_FASTLOGIN", "REGEXP_NUMBER", "REGEXP", "JE_SMS_TIMEOUT")
                        .selectColumns("CODE,VALUE"));
        for (DynaBean setting : list) {
            dynaBean.set(setting.getStr("CODE"), setting.getStr("VALUE"));
        }
        //
        return dynaBean;
    }

    @Override
    public InputStream getPicture(String type, String code) {
        DynaBean dynaBean = null;
        if (StringUtil.isNotEmpty(code)) {
            dynaBean = metaService.selectOne("JE_CORE_SETPLAN", ConditionsWrapper.builder().eq("JE_SYS_PATHSCHEME", code));
        } else {
            dynaBean = metaService.selectOne("JE_CORE_SETPLAN", ConditionsWrapper.builder().eq("SETPLAN_IS_DEFULT", "1"));
        }
        //backgroundLogo,leftImg,browserIcon,titleLogo,thumbnail
        String str = "";
        if ("backgroundLogo".equals(type)) {
            //网页背景图
            str = dynaBean.getStr("JE_SYS_BACKGROUNDLOGO");
        }
        if ("leftImg".equals(type)) {
            //左侧信息图
            str = dynaBean.getStr("JE_SYS_LEFTIMG");
        }
        if ("browserIcon".equals(type)) {
            //浏览器显示图标
            str = dynaBean.getStr("JE_SYS_ICON");
        }
        if ("titleLogo".equals(type)) {
            //系统标题图（logo）
            str = dynaBean.getStr("JE_SYS_TITLELOGO");
        }
        if ("thumbnail".equals(type)) {
            str = dynaBean.getStr("JE_SYS_BACKGROUNDLOGO");
        }
        JSONObject jsonObject = new JSONObject();
        Object object = JSON.parse(str);
        if (object instanceof JSONObject) {
            jsonObject = (JSONObject) object;
        }
        if (object instanceof JSONArray) {
            JSONArray jsonArray = (JSONArray) object;
            if (jsonArray != null && jsonArray.size() > 0) {
                jsonObject = jsonArray.getJSONObject(0);
            }
        }
        if ("thumbnail".equals(type)) {
            File thumbnail = documentInternalRpcService.readThumbnail(jsonObject.getString("fileKey"));
            return FileUtil.getInputStream(thumbnail);
        }
        if (Strings.isNullOrEmpty(jsonObject.getString("fileKey"))) {
            return new ByteArrayInputStream(new byte[0]);
        }
        File file = documentInternalRpcService.readFile(jsonObject.getString("fileKey"));
        return FileUtil.getInputStream(file);
    }


}
